try {
    Type.registerNamespace('TransInUtil');   
    TransInUtil.checkWhenCommit = function(itemKey, scanCount, scanNum) {
		var sql = " where cgeneralbid in ('0'";
		for(var i = 0; i < itemKey.length; i++) {
			sql = sql + ",'" + itemKey[i] + "'";
		}
		sql = sql + ")";
		var checkResult="";
		NCMMPubUtil.queryVO(TransInScanVO, sql, function(scanData) {
			if(typeof(scanData) == 'undefined' || scanData == null || scanData.length == 0) {
				return;
			}
			var countNum = {};
			var vos = {};
			var data = eval(scanData);
			for(var i = 0; i < data.length; i++) {	
				if(NCMMPubUtil.isEmpty(countNum)||NCMMPubUtil.isEmpty(countNum[data[i].cgeneralbid])) {
					countNum[data[i].cgeneralbid] = 1;
					vos[data[i].cgeneralbid] = data[i];
				} else {
					countNum[data[i].cgeneralbid] = countNum[data[i].cgeneralbid] + 1;
				}
			}
			for(var i = 0; i < itemKey.length; i++) {
				var vo = vos[itemKey[i]];
				if(countNum[itemKey[i]] != scanCount[itemKey[i]]) {
					checkResult= "单据号" + vo.vbillcode + "物料" + vo.cmaterialvid_name + "必须选中其所有扫描记录才能提交！";
				} 
			}
		});
		return checkResult;
	};
	TransInUtil.getScanVOCount = function(cgeneralhid) {
	    var len=0;
		var wheresql = "where cgeneralbid='"+ cgeneralhid+"'";
		NCMMPubUtil.queryVO(TransInScanVO, wheresql,function(scanData) {
			if(typeof(scanData) == 'undefined' || scanData == null || scanData.length == 0) {
				return;
			}
			var data = eval(scanData);	
			len= data.length;
		});
		return len;
	};
    TransInUtil.commitData=function(billinfos,scanpk,callback){
        $js.showLoadingBar();	 
	    //测试连接
		var rtn=NCMMDBUtil.testNCConnection(function(data) {
			if(data == false || data == "false") {
				$js.hideLoadingBar();
				$toast("连接服务器失败，无法提交！");
				return false;
			} else {			   
				var tmprtn=NCMMDBUtil.submitLocaldataToNC("4Y_4Esave", billinfos, function(commitInfo) {
					$js.hideLoadingBar();
					if(!NCMMPubUtil.isEmpty(commitInfo)) {
						if(commitInfo.return == null || commitInfo.return == "") {
							$alert("提交失败：" + $jsonToString(commitInfo));
							return false;
						} else if(commitInfo["return"].returnFlag == 1) {
												//$alert("return="+$jsonToString(commitInfo));
							var billbids = commitInfo.billbids;
							TransInUtil.deleteVOsAfterCommit(scanpk,billbids);
							if(callback != null && callback != undefined && typeof(callback) == 'function') {                                 
                                    callback(billbids);
                                }
                            $toast("提交成功！");								
							return true;						
						} else {
							$alert("提交失败" + $jsonToString(commitInfo.return.returnDesc));
							return false;
						}
					} else {
						$alert("提交失败");
						return false;
					}
				});
				return tmprtn;
			}
		});
		if(rtn){
		  $alert("rtn=true");
		}
		
		return rtn;
	};
	TransInUtil.deleteVOsAfterCommit = function(scanpk,billbids) {
		var sql =""; 
		//if(NCMMPubUtil.isEmpty(scanpk)){
			sql=" cgeneralbid in ('0'";
			for(var i = 0; i < billbids.length; i++) {
				sql = sql + ",'" + billbids[i] + "'";
			}
			sql = sql + ")";
		//}
		//else{
		//	sql=" pk_transinscan ='"+scanpk+"'";
		//}
		deleteVOByWhere(TransInScanVO, sql);
		deleteVOByWhere(TransInVO, sql);
		//判断 如果扫描主数量大于等于主数量 删除订单
			
	};
	function deleteVOByWhere (VOClass, whereSql) {
        var tblname = VOClass.prototype.getTableName();
        var sql = "delete from " + tblname + " where " + whereSql;
        var param = {
            db: NCMMPubUtil.DatabaseName,
            sql: sql
        }
        //$alert("sql1="+sql);
        $sqlite.execSql(param);
       // $alert("11");
    };
    
    TransInUtil.updateBillAfterCommit=function(cgeneralbid,num,nastnum){
	   var wheresql = "where cgeneralbid='"+ cgeneralbid+"'";
	 
	   NCMMPubUtil.queryVO(TransInVO, wheresql,function(data) {
	       var vos = eval(data);
	       vos = NCMMPubUtil.htmlspecialjsonarray2UI(vos);
                if(vos == null || vos.length == 0) {
               
                    return;
                }             
                //调拨入库，提交完清除本地单据
               // var newnum= TransInUtil.getSubNum(vos[0]["nscanednum"],num);
               // var newnastnum= TransInUtil.getSubNum(vos[0]["nscanedastnum"],nastnum);
               // vos[0]["nscanednum"]=newnum;
               // vos[0]["nscanedastnum"] = newnastnum;
              //  vos[0]["nsubmitnum"]= TransInUtil.getAddNum(vos[0]["nsubmitnum"],num);                   
              //  var ncanscanedNum=TransInUtil.getSubNum(parseFloat(vos[0]["nnum"]),vos[0]["nsubmitnum"]);                
              //  if(ncanscanedNum<=0){                     
                    //$alert("sql=");           
                    NCMMPubUtil.deleteVO(TransInVO,vos[0]);
              //  }
              //  else{            
              //      NCMMPubUtil.updateVO(TransInVO, vos[0]);
               // }	  
	        });
	 }
	 TransInUtil.getAddNum=function(num1,num2){
       if(num1 == null || num1 == "") {
            num1 += "00.00000";
        } else {
            num1 = parseFloat(num1);
        }
        if(num2 == null || num2 == "") {
            num2 += "1.00000";
        } else {
            num2 = parseFloat(num2);
        }
        var newNum = parseFloat(num1).add(parseFloat(num2));
        return newNum; 
    };
    
    //批量插入
    TransInUtil.batchInsertTableVOs = function(VOClass, vos) {
        if (NCMMPubUtil.isEmpty(vos)) {
            return;
        }
        var attrs = VOClass.prototype.getAllAttrs();
        var fields = attrs.map(function(row, i, arr) {
            return row.name;
        });
        var valueMapList = Array.prototype.map.call(vos, function(row, i, arr) {
            var billinfo_local = $stringToJSON((row || {}));
            var values = attrs.map(function(attr, i, array) {
                var fname = attr.name;
                if (!!billinfo_local[fname]) {
                    if (billinfo_local[fname] != "" && typeof (billinfo_local[fname]) == "string") {
                        billinfo_local[fname] = NCMMPubUtil.htmlspecialchars2sqliteex(billinfo_local[fname]);
                    }
                    return billinfo_local[fname];
                } else {
                    if (attr.type == NCMMPubUtil.VALUE_TYPE_INTEGER) {
                        return 0;
                    } else if (attr.type == NCMMPubUtil.VALUE_TYPE_REAL) {
                        return 0.0;
                    } else {
                        return "";
                    }
                }
            });
            return values;
        });
        var sum = valueMapList.length;
        $app.replaceBatch({
            db : NCMMPubUtil.DatabaseName,
            table : VOClass.prototype.getTableName(),
            fields : fields,
            values : valueMapList,
            callback : null
        });
        return sum;
    }
    
    //批量更新
    TransInUtil.updateBatchVOs = function(VOClass, vos, scanedname) {
        if (NCMMPubUtil.isEmpty(vos)) {
            return;
        }
        var attrs = VOClass.prototype.getAllAttrs();
        var fields = [];
		for (var i = 0; i < attrs.length; i++) {
			if (attrs[i].name != scanedname) {
				fields.push(attrs[i].name);
			}
		}
		var values = [];
        for (var j = 0; j < vos.length; j++) {
			var row = $stringToJSON((vos[j] || {}));
			var rowVaules = [];
			for (var k = 0; k < attrs.length; k++) {
				var fname = attrs[k].name;
				var type=attrs[k].type;
				if (fields != scanedname) {
					if (!!row[fname]) {
						if (row[fname] != "" && typeof (row[fname]) == "string") {
							row[fname] = NCMMPubUtil.htmlspecialchars2sqliteex(row[fname]);
						}
						rowVaules.push(row[fname]);
					} else {
						if (type == NCMMPubUtil.VALUE_TYPE_INTEGER) {
							rowVaules.push(0);
						} else if (type == NCMMPubUtil.VALUE_TYPE_REAL) {
							rowVaules.push(0.0);

						} else {
							rowVaules.push("");
						}
					}
				}
			}
			values.push(rowVaules);
		}
        var sum = rowVaules.length;
        $app.replaceBatch({
            db : NCMMPubUtil.DatabaseName,
            table : VOClass.prototype.getTableName(),
            fields : fields,
            values : values,
            callback : null
        });
        return sum;
    }
    
    //主数量除以换算率得辅数量 
    TransInUtil.getAstnum =  function (nnum,vchange){
        var nastum=nnum;
        if(nnum == null || nnum == "") {
            nnum += "00.00000";
        } else {
            nnum = parseFloat(nnum);
        }
        if(vchange == null || vchange == "") {
            vchange += "1.00000";
        } else {
            var crArray = vchange.split("/");
            if(crArray == null || crArray.length != 2){
                return nastum; 
            }
            var cru = parseFloat(crArray[0]);
            var crd = parseFloat(crArray[1]);
            if(cru == null || crd == null){
                return nastum;
            }
            nastum=(crd*nnum)/cru;
            if(!isBitEnByBitNum(nastum,8)){
                nastum=nastum.toFixed(8);
            }
        }
        return nastum;
    }
    
    //计算主数量
    TransInUtil.getNum =  function (nastnum,vchange) {
        var num=nastnum;
        if(nastnum == null || nastnum == "") {
            nastnum += "00.00000";
        } else {
            nastnum = parseFloat(nastnum);
        }
        if(vchange == null || vchange == "") {
            vchange += "1.00000";
        } else {
            var crArray = vchange.split("/");
            if(crArray == null || crArray.length != 2) {
                return num;
            }
            var cru = parseFloat(crArray[0]);
            var crd = parseFloat(crArray[1]);
            if(cru == null || crd == null){
                return num;
            }
            num=(cru*nastnum)/crd;
            if(!isBitEnByBitNum(num,8)){
                num=num.toFixed(8);
            }
        }
        return num;
    }
    
    function isBitEnByBitNum(num,bitnum){
        var rtn=false;
        var stringNum=num.toString();
        var bitNumberIndex = stringNum.indexOf('.');
        //整数
        if(bitNumberIndex<0){
            if(bitnum>=0){
                rtn=true;
            }
        }
        else if((stringNum.length-1-bitNumberIndex)<=bitnum){
            rtn=true;
        }
        return rtn;
    }
    
    //计量单位处理
    TransInUtil.getUnitBitnumber = function(unitid) {
        var wheresql = "where pk_measdoc='"+ unitid+"'";
        var bitnumber=0;
        if(!NCMMPubUtil.isTableExist(MeasdocVO) ){
            return;
        }
        NCMMPubUtil.queryVO(MeasdocVO, wheresql, function(data) {
           if(typeof(data) == 'undefined' || data == null || data.length == 0) {
               return;
           }
           var unitData = eval(data);
           if(unitData.length>0){
               bitnumber=unitData[0].bitnumber;
           } else {
               return;
           }
        });
        return bitnumber;
    }
    
    //更新调拨入库节点列表扫描数量 
    TransInUtil.updateTransInScanedNum= function(cgeneralbid) {
        var wheresql = "where cgeneralbid='"+ cgeneralbid+"'";
        NCMMPubUtil.queryVO(TransInScanVO, wheresql, function(scanData) {
            var num = 0;
            var astnum = 0;
            console.log("scandata = "+$jsonToString(scanData));
            if(NCMMPubUtil.isNotEmpty(scanData)){
                var scanvos = eval(scanData);
                for(var i = 0; i < scanvos.length; i++) {
                    num = getAddScanedNum(num, scanvos[i].nscannum);
                    astnum = getAddScanedNum(astnum, scanvos[i].nscanastnum);
                }
            }
            NCMMPubUtil.queryVO(TransInVO, wheresql, function(data) {
               if(typeof(data) == 'undefined' || data == null || data.length == 0) {
                   return;
               }
               var vos = eval(data);
               vos = NCMMPubUtil.htmlspecialjsonarray2UI(vos);
               if(vos == null || vos.length == 0) {
                   return;
               }
               vos[0]["nscanednum"] = num;
               vos[0]["nscanedastnum"] = astnum;
               NCMMPubUtil.updateVO(TransInVO, vos[0]);
            });
        });
    }
    
    function getAddScanedNum(scanedNum, currentScanedNum) {
        if(scanedNum == null || scanedNum == "") {
            scanedNum += "00.00000";
        } else {
            scanedNum = parseFloat(scanedNum);
        }
        if(currentScanedNum == null || currentScanedNum == "") {
            currentScanedNum += "1.00000";
        } else {
            currentScanedNum = parseFloat(currentScanedNum);
        }
        var newScanedNum = parseFloat(scanedNum).add(parseFloat(currentScanedNum));
        return newScanedNum;
    }
    
    //小数点位数多余某位，则四舍五入
    TransInUtil.decimalPrecision =function(num,bitnumber) {
        var floatNum = parseFloat(num);
        if(isNaN(floatNum)||isNaN(bitnumber)) {
            return "NaN";
        }
        if(bitnumber==0){
            return parseInt(floatNum);
        }
        bitnumber=parseFloat(bitnumber);
        var t = 1;
        var tmpbitnumber=bitnumber;
        for(; tmpbitnumber > 0; t *= 10, tmpbitnumber--);
        floatNum = Math.round(floatNum * t) / t;
        return floatNum;
    }
    
    TransInUtil.isBsBitnumber = function(num,unitid) {
        var unitBitnum=TransInUtil.getUnitBitnumber(unitid);
        if(NCMMPubUtil.isEmpty(unitBitnum)) {
            return false;
        }
        if(num.split(".").length==1) {
            return false;
        }
        var numBitNum=num.split(".")[1].length;
        if(numBitNum>unitBitnum){
            return true;
        }
        return false;
    }
    
    //调拨入库节点下拉菜单
    TransInUtil.openDropDownList = function(controlid) {
        $menu.openDropDownList({
			"controlid": controlid, //目标控件的id
			"dropDownListWidth": "100", //菜单项的宽度
			"background": "#f2f2f2",
			//"background-image":"app.png",
			"color": "#ee4311",
			"font-size": "12",
			"halign": "center", //right  center
			"split-color": "#ee4311",
			//"margin-left":"10",
			"panelstyle": "round-div",
			"border-color": "#ee4311",
			//"showtype":"right",
			"dropItemsArray": [{
				"id": "id_homepage",
				"name": "主菜单", //菜单项名称
				"action": "gotohomepage()" //点击该菜单项时执行的JS方法
			}, {
				"id": "id_datamanage",
				"name": "数据管理", //菜单项名称
				"action": "gotodatamanage()" //点击该菜单项时执行的JS方法
			}, {
				"id": "id_setting",
				"name": "业务设置", //菜单项名称
				"action": "setting()" //点击该菜单项时执行的JS方法
			}, {
				"id": "id_logout",
				"name": "注销", //菜单项名称
				"action": "logout()" //点击该菜单项时执行的JS方法
			}, {
				"id": "id_scanlist",
				"name": "扫描记录", //菜单项名称
				"action": "gotoscanlist()" //点击该菜单项时执行的JS方法
			}]
		});
    }
    function gotohomepage() {
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.HomePage", //目标页面（首字母大写）全名
			"isKeep": "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
		});
	}
	function gotodatamanage() {
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.DM_main", //目标页面（首字母大写）全名
			"isKeep": "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
		});
	}
	function setting() {
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.BusinessSettingPage", //目标页面（首字母大写）全名
			"isKeep": "true", //打开新页面的同时是否保留当前页面，true为保留，false为不保留
		});
	}
	function logout() {
		//$view.close();
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.LoginPage", //目标页面（首字母大写）全名
			"isKeep": "false", //打开新页面的同时是否保留当前页面，true为保留， false为不保留
		});
	}
	function gotoscanlist() {
		//$view.close();
		$view.open({
			"viewid": "com.yonyou.ncmm_pac_pda.TransInScanList", //目标页面（首字母大写）全名
			"isKeep": "true", //打开新页面的同时是否保留当前页面，true为保留， false为不保留
		});
	}
} catch(e) {
	$e(e);
}